/**
 * @author 徐楠
 * @date 2022/5/5 18:41
 * @version 1.0
 */

package com.xunan.likou;

import java.util.ArrayList;
import java.util.List;

public class FractionalAdditionAndSubtraction {
    public static void main(String[] args) {
        String expression1 = "-122/332+1/2";
        String expression2 = "1/2-1/2";
        String expression3 = "1/2+1/2";
        String expression4 = "1/3-1/2";
        String s = fractionAddition(expression4);
        System.out.println(s);
    }

    public static String fractionAddition(String expression) {
        List<Integer> fz = new ArrayList<>();
        List<Integer> fm = new ArrayList<>();
        //flag1代表-，+；flag2代表'/'
        int flag1 = 0;
        int flag2 = 0;
        int n = expression.length();
        for (int i = 0; i < n; i++) {
            if (expression.charAt(i) == '+') {
                flag1 = i;
            }

            if (expression.charAt(i) == '-') {
                flag1 = i;
            } else if (expression.charAt(i) == '/') {
                flag2 = i + 1;
            } else if (i == n - 1 || expression.charAt(i + 1) == '+' || expression.charAt(i + 1) == '-') {
                //substring 从startIndex开始数，不包括endIndex位置的字符
                System.out.println(flag1);
                System.out.println(flag2 - 1);

                System.out.println(flag2);
                System.out.println(i - flag2 + 1);
                System.out.println();
                System.out.println(i);
                System.out.println("----------");

                //分子取值全部保留符号
                fz.add(Integer.valueOf(expression.substring(flag1, flag2 - 1)));
                fm.add(Integer.valueOf(expression.substring(flag2, i + 1)));

            }
        }

        //求分母的最小公倍数
        int lcmnum = 1;
        for (Integer integer : fm) {
            lcmnum = lcm(lcmnum, integer);
        }
        //通分后的分子和
        int fzsum = 0;
        for (int i = 0; i < fz.size(); i++) {
            fzsum += lcmnum / fm.get(i) * fz.get(i);
        }
        int gcdNum = gcd(fzsum, lcmnum);//求分子和分母的最大公约数

        int a = fzsum / gcdNum;
        int b = lcmnum / gcdNum;
        if ((a > 0 && b > 0) || (a < 0 && b < 0) || (a == 0)) {
            return Math.abs(a) + "/" + Math.abs(b);
        } else {
            return "-" + Math.abs(a) + "/" + Math.abs(b);
        }

    }

    /**
     * 求最大公约数
     */
    public static int gcd(int a, int b) {
        if (a % b == 0)
            return b;
        return gcd(b, a % b);
    }

    /**
     * 求最小公约数
     */
    public static int lcm(int x, int y) {
        int gcd = gcd(x, y);
        return (x / gcd) * (y / gcd) * gcd;
    }


}
